package com.quantanetwork.esm.port;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.BeansException;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public final class SpringBeansUtil
{
	private static ClassPathXmlApplicationContext cpxac = null;

	private static List<String> list(File file, String suffix)
	{
		List<String> rtnVal = null;
		File files[] = file.listFiles();
		if (files != null)
		{
			for (File file2 : files)
			{
				if (file2.isDirectory())
				{
					List<String> rtnTemp = list(file2, suffix);
					if (rtnTemp != null)
					{
						if (rtnVal == null)
						{
							rtnVal = new ArrayList<String>();
						}
						rtnVal.addAll(rtnTemp);
					}
				}
				else
				{
					if (file2.getName().toLowerCase().endsWith(suffix.toLowerCase()))
					{
						if (rtnVal == null)
						{
							rtnVal = new ArrayList<String>();
						}
						rtnVal.add(file2.getName());
					}
				}
			}
		}
		return rtnVal;
	}

	public static void loadXmls(String suffix) throws BeansException
	{
		String classPath[] = System.getProperty("java.class.path").split("[;]");
		List<String> files = null;
		for (String path : classPath)
		{
			File file = new File(path);
			if (file.isDirectory() == false)
			{
				continue;
			}
			List<String> rtnVal = list(file, suffix);
			if (rtnVal != null)
			{
				if (files == null)
				{
					files = new ArrayList<String>();
				}
				files.addAll(rtnVal);
			}
		}
		if (files != null)
		{
			String xml[] = new String[files.size()];
			files.toArray(xml);
			loadXml(xml);
		}
	}

	public static void loadXml(String xmlFile[]) throws BeansException
	{
		cpxac = new ClassPathXmlApplicationContext(xmlFile);
	}

	public static void loadXml(String xmlFile) throws BeansException
	{
		cpxac = new ClassPathXmlApplicationContext(xmlFile);
	}

	public static Object getBeanObj(String beanId) throws BeansException
	{
		return cpxac.getBean(beanId);
	}

	public static Object getBeanObj(String beanId, Class<?> className) throws BeansException
	{
		return cpxac.getBean(beanId, className);
	}
}
